package com.fintech.pangu.autoconfigure.actuate.metrics.rocketmq;

import com.fintech.pangu.actuate.metrics.rocketmq.MicrometerRocketMQMetricsCollector;
import com.fintech.pangu.rocketmq.core.consumer.DefaultRocketMQListenerContainer;
import com.fintech.pangu.rocketmq.core.producer.RocketMQTemplate;
import com.fintech.pangu.rocketmq.core.producer.hook.SendMessageMetricHookImpl;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;

/**
 * 通过BeanPostProcessor为RocketMQ组件设置具体的RocketMQMetricsCollector指标收集器
 */
public class RocketMQMetricsPostProcessor implements BeanPostProcessor {

    // 构造注入，用于获取MeterRegistry
    private ApplicationContext context;

    private MeterRegistry meterRegistry;
    private MicrometerRocketMQMetricsCollector micrometerRocketMQMetricsCollector;

    public RocketMQMetricsPostProcessor(ApplicationContext context) {
        this.context = context;
    }


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 由于DefaultRocketMQListenerContainer在InitializingBean接口初始化时会启动consumer，故先设置MicrometerRocketMQMetricsCollector
        if (bean instanceof DefaultRocketMQListenerContainer) {
            ((DefaultRocketMQListenerContainer) bean).setRocketMQMetricsCollector(getMicrometerRocketMQMetricsCollector());
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RocketMQTemplate) {
            ((RocketMQTemplate) bean).setRocketMQMetricsCollector(getMicrometerRocketMQMetricsCollector());
        }

        if (bean instanceof SendMessageMetricHookImpl) {
            ((SendMessageMetricHookImpl) bean).setRocketMQMetricsCollector(getMicrometerRocketMQMetricsCollector());
        }



        return bean;
    }




    public MicrometerRocketMQMetricsCollector getMicrometerRocketMQMetricsCollector(){
        if (this.micrometerRocketMQMetricsCollector == null) {
            synchronized (this){
                if (this.micrometerRocketMQMetricsCollector == null) {
                    this.micrometerRocketMQMetricsCollector = this.context.getBean(MicrometerRocketMQMetricsCollector.class);
                }
            }
        }
        return this.micrometerRocketMQMetricsCollector;
    }

}
